#include"myfile.h"
 #include <fcntl.h>
#include<stdlib.h>
#include<assert.h>
#include<unistd.h>
_FILE*_fopen(char*path,char*model)
{
	int md;
	int fd;
	if(strcmp(model,"w")==0)
	{
		md = O_CREAT|O_WRONLY|O_TRUNC;
	}
	else if(strcmp(model,"a")==0)
	{
		md = O_CREAT|O_WRONLY|O_APPEND;
	}
	else if(strcmp(model,"r")==0)
	{
		md = O_RDONLY;
	}
	else
	{
		return NULL;
	}
	
		fd = open(path,md,0666);
		if(fd<0)
		{
			return NULL;
		}
		_FILE*file =(_FILE*) malloc(sizeof(_FILE));
		if(file ==NULL)
		{	
			return NULL;
		}
		file->fd = fd;
		file->outpos = 0;
		file->MODEL = 2;
		return file;
}

int _fwrite(char*des,size_t len,_FILE*file)
{
	memcpy(file->buff,des,len);
	file->outpos = len;
	if(file->MODEL == 1)
	{
		file->outpos += len;
		if(file->outpos >SIZE)
		{
			write(file->fd,file->buff,file->outpos);
			file->outpos = 0;
			return file->outpos;
		}
	}
	else if(file->MODEL == 2)
	{
		if(file->buff[file->outpos-1]== '\n')
		{
			write(file->fd,file->buff,len);
			file->outpos = 0;
			return len;
		}
	}
	else if(file->MODEL == 4)
	{
		write(file->fd,file->buff,len);
		file->outpos = 0;
		return len;
	}
	return -1;
}
void _fflush(_FILE*file)
{
	if(file->outpos)
	{
		write(file->fd,file->buff,file->outpos);
		file->outpos = 0;
	}
	return ;
}
void _fclose(_FILE*file)
{
	assert(file);
	_fflush(file);
	close(file->fd);
}
